#include "cepollworkthread.h"
#include "cclientdata.h"
#include "ctagdata.h"
#include "clogoper.h"
#include "cglobal.h"
#include "cepollclientdatamgr.h"
#include "cpublicdata.h"

#include <QThread>
#include <QFile>

CEpollWorkThread::CEpollWorkThread(int nSocketFd)
{
    m_nSocketFd = nSocketFd;
    m_bConnected = false;
    m_pClient = nullptr;
    m_nReplyByte0 = CPublicData::instance().m_stServerCfg.m_nReplyByte0;
    m_nReplyByte1 = CPublicData::instance().m_stServerCfg.m_nReplyByte1;
}

void CEpollWorkThread::run()
{
    QByteArray byteBuffer;
    while (readData(byteBuffer))
    {
        CClientProcess* pProcess = CEpollClientDataMgr::getClientProcess(m_nSocketFd);
        if (pProcess == nullptr) continue;
        if (pProcess->m_pClient == nullptr) pProcess->m_pClient = m_pClient;
        //连接处理返回信号，但避免重复连接
        if (false == pProcess->m_bRecvConnected)
        {
            connect(pProcess, &CClientProcess::sigSendRecvStatus, this
                    , &CEpollWorkThread::slotHandleRecvStatus, Qt::QueuedConnection);
            connect(pProcess, &CClientProcess::sigLogMsg, this
                    , &CEpollWorkThread::sigRunningLogMsg, Qt::QueuedConnection);
            pProcess->m_bRecvConnected = true;
        }
        //加入解析队列
        pProcess->appendRecvData(byteBuffer);
        byteBuffer.clear();
        continue;
    }
}

bool CEpollWorkThread::readData(QByteArray &byteBuffer)
{
    char szTempBuffer[DEF_TEMP_MAX];
    if (m_nSocketFd < 0) return false;
    int nLen = recv(m_nSocketFd, szTempBuffer, sizeof(szTempBuffer), 0);
    if (nLen <= 0)
    {
        if (nLen == 0)
        {
            emit sigConnectionClosed(m_nSocketFd);
        }
//        else
//        {
//            QString sMsg = A2T("读取报文失败:") + QString::number(errno) + A2T(",原因：") + QString(strerror(errno));
//            emit sigRunningLogMsg(m_nSocketFd, enDevAlarm, A2T("Tcp服务端"), sMsg);
//        }
        return false;
    }
    byteBuffer.append(szTempBuffer, nLen);
    return true;
}

bool CEpollWorkThread::slotHandleRecvStatus(bool bRtn)
{
    char szBuffer[2];
    memset(szBuffer, 0, 2);
    szBuffer[0] = m_nReplyByte0;
    if (true == bRtn) szBuffer[0] = m_nReplyByte1;
    send(m_nSocketFd, szBuffer, 1, MSG_DONTWAIT);
    qDebug() << QString("Reply client %1 with %2").arg(m_nSocketFd).arg(m_nReplyByte1);
    return bRtn;
}
